<?php
/**
 * 直接调拨单
 * Created by PhpStorm.
 * User: echa
 * Date: 2018/2/1
 * Time: 17:11
 */
namespace App\Services\Warehouse;


use App\Repositories\Warehouse\WarehouseRepository;

class DirectTransfersService extends PublicService {
    //直接调拨表单ID
    //protected $Formid = 'STK_TransferDirect';

    protected $WarehouseService;
    protected $WarehouseRepository;
    public function __construct(WarehouseService $warehouseService,WarehouseRepository $warehouseRepository)
    {
        parent::__construct(Config('k3cloud.DirectTransfers'));
        $this->WarehouseService=$warehouseService;
        $this->WarehouseRepository=$warehouseRepository;
    }

    /**
     * 保存
     * 1.formid：业务对象表单Id（必录）
     * 2.data：Json格式数据（详情参考Json格式数据）（必录）
     * 2.1.Creator：创建者名字（非必录）
     * 2.2.NeedUpDateFields：需要保存的字段,格式["fieldkey1","fieldkey2","entitykey1",...]，数组类型(非必录)
     * 2.3.NeedReturnFields：需要返回的结果字段,格式["fieldkey","entitykey.fieldkey",...]（非必录）
     * 2.4.IsDeleteEntry：是否删除分录，默认True删除（非必录）
     * 2.5.SubSystemId：菜单所在子系统Id（非必录）
     * 2.6.IsVerifyBaseDataField：是否验证所有的基础资料，默认False不验证（非必录）
     * 2.7.IsEntryBatchFill：是否批量填充分录：默认为Ture（非必录）
     * 2.8.Model：表单实体数据（必录）
     */
    public function SaveDirectTransfers($arrdata = [],$is_submitandaudit=false)
    {
            if(empty($arrdata['FID'])){
                $arrdata['FID']=0;
            }
            if(empty($arrdata['FBillNo'])){
                $arrdata['FBillNo']="";
            }
            $FOwnerTypeBDSupplier=config('k3cloud.FOwnerTypeBDSupplier');
            $FOwnerTypeBDOwnerOrg=config('k3cloud.FOwnerTypeBDOwnerOrg');
            $FOwnerFNumber=config('k3cloud.organization');
            $FOwnerFNumberOut=$FOwnerFNumber;
            if($arrdata['k3_vmi']){
                $FOwnerTypeID=$FOwnerTypeBDSupplier;
                $FOwnerFNumber=$arrdata['k3_supplier_sn'];
            }else{
                $FOwnerTypeID=$FOwnerTypeBDOwnerOrg;
            }
            if($arrdata['k3_vmi_out']){
                $FOwnerTypeIDOut=$FOwnerTypeBDSupplier;
                $FOwnerFNumberOut=$arrdata['k3_supplier_sn_out'];
            }else{
                $FOwnerTypeIDOut=$FOwnerTypeBDOwnerOrg;
            }
            if(empty($arrdata['Note'])){
                $arrdata['Note']='';
            }
            $goods=$this->PostGoodsData($arrdata['GoodsData']);
            $data = [
                    "FID"=>$arrdata['FID'],
                    "FBillNo"=>$arrdata['FBillNo'],
                    "FBillTypeID"=>[
                        "FNumber"=>"ZJDB01_SYS"
                    ],
                    "FBizType"=>"NORMAL",
                    "FTransferDirect"=>"GENERAL",
                    "FTransferBizType"=>"InnerOrgTransfer",
                    "FSettleOrgId"=>[
                        "FNumber"=>config('k3cloud.organization')
                    ],
                    "FSaleOrgId"=>[
                        "FNumber"=>config('k3cloud.organization')
                    ],
                    "FStockOutOrgId"=>[
                        "FNumber"=>config('k3cloud.organization')
                    ],
                    "FOwnerTypeOutIdHead"=>$FOwnerTypeIDOut,
                    "FOwnerOutIdHead"=>[
                        "FNumber"=>$FOwnerFNumberOut
                    ],
                    "FStockOrgId"=>[
                        "FNumber"=>config('k3cloud.organization')
                    ],
                    "FIsIncludedTax"=>false,
                    "FIsPriceExcludeTax"=>false,
                    "FOwnerTypeIdHead"=>$FOwnerTypeID,
                    "FSETTLECURRID"=>[
                        "FNumber"=>"PRE001"
                    ],
                    "FOwnerIdHead"=>[
                        "FNumber"=>$FOwnerFNumber
                    ],
                    "FStockerId"=>[
                        "FNumber"=>""
                    ],
                    "FStockerGroupId"=>[
                        "FNumber"=>""
                    ],
                    "FDate"=>date('Y-m-d H:i:s',time()),
                    "FNote"=>$arrdata['Note'],
                    "FBaseCurrId"=>[
                        "FNumber"=>"PRE001"
                    ],
                    "FSUPPLIERID"=>[
                        "FNumber"=>""
                    ],
                    "FCustID"=>[
                        "FNumber"=>""
                    ],
                    "FScanBox"=>"",
                    "FThirdSystem"=>"",
                    "FThirdSrcBillNo"=>"",
                    "FThirdSrcId"=>"",
                    "FBillEntry"=>$goods
                ];
           if($is_submitandaudit){
               $return=$this->save($data);
               if(empty($return['Id'])){
                   return false;
               }
               $submitreturn=$this->SubmitDirectTransfers([$return['Number']]);
               if(empty($submitreturn['Id'])){
                   return false;
               }
               $auditreturn=$this->AuditDirectTransfers([$return['Number']]);
               if(empty($auditreturn['Id'])){
                   return false;
               }
               return $auditreturn;
           }else{
               return $this->save($data);
           }
    }


    /**
    提交
     *
     * 1.formid：业务对象表单Id（必录）
    2.data：Json格式数据（详情参考Json格式数据）（必录）
    2.1.CreateOrgId：创建者组织，字符串类型（非必录）
    2.2.Numbers：单据编号集合，格式["billNo1","billNo1",...]，数组类型（必录）
     */

    public function  SubmitDirectTransfers($Numbers=[]){
        return $this->submit($Numbers);
    }

    /**
    审核
     * 1.formid：业务对象表单Id（必录）
    2.data：Json格式数据（详情参考Json格式数据）（必录）
    2.1.CreateOrgId：创建者组织，字符串类型（非必录）
    2.2.Numbers：单据编号集合，格式["billNo1","billNo1",...]，数组类型（必录）
     */
    public function AuditDirectTransfers($Numbers=[]){
        return $this->audit($Numbers);
    }

    /**
     *   获取明细商品数据列表
     *
     */
    private function PostGoodsData($GoodsData)
    {
        if (!is_array($GoodsData)) {
            return false;
        }
        $goods=array();
        $FOwnerTypeBDSupplier=config('k3cloud.FOwnerTypeBDSupplier');
        $FOwnerTypeBDOwnerOrg=config('k3cloud.FOwnerTypeBDOwnerOrg');
        foreach ($GoodsData as $k => $v) {
            $FOwnerFNumber=config('k3cloud.organization');
            $FOwnerFNumberOut=$FOwnerFNumber;
            if($v['k3_vmi']){
                $FOwnerTypeID=$FOwnerTypeBDSupplier;
                $FOwnerFNumber=$v['k3_supplier_sn'];
            }else{
                $FOwnerTypeID=$FOwnerTypeBDOwnerOrg;
            }
            if($v['k3_vmi_out']){
                $FOwnerTypeIDOut=$FOwnerTypeBDSupplier;
                $FOwnerFNumberOut=$v['k3_supplier_sn_out'];
            }else{
                $FOwnerTypeIDOut=$FOwnerTypeBDOwnerOrg;
            }
            $goods[] = [
                "FEntryID"=>null,
                "FMaterialId"=>[
                    "FNumber"=>$v['goods_sn']
                ],
                "FUnitID"=>[
                    "FNumber"=>$v['spec_unit']
                ],
                "FQty"=>$v['goods_number'],
                "FLot"=>[
                    "FNumber"=>""
                ],
                "FSrcStockId"=>[
                    "FNumber"=>$v['StockNubmer']
                ],
                "FPrice"=>0.0,
                "FDestStockId"=>[
                    "FNumber"=>$v['DestStockNubmer']
                ],
                "FBomId"=>[
                    "FNumber"=>""
                ],
                "FSrcStockStatusId"=>[
                    "FNumber"=>"KCZT01_SYS"
                ],
                "FDeliChkQualifyType"=>"",
                "FAmount"=>0.0,
                "FProduceDate"=>null,
                "FDestStockStatusId"=>[
                    "FNumber"=>"KCZT01_SYS"
                ],
                "FMtoNo"=>null,
                "FBusinessDate"=>date('Y-m-d H:i:s',time()),
                "FExpiryDate"=>null,
                "FOwnerTypeOutId"=>$FOwnerTypeIDOut,
                "FOwnerOutId"=>[
                    "FNumber"=>$FOwnerFNumberOut
                ],
                "FOwnerTypeId"=>$FOwnerTypeID,
                "FOwnerId"=>[
                    "FNumber"=>$FOwnerFNumber
                ],
                "FNoteEntry"=>$v['goods_remark'],
                "FProjectNo"=>null,
                "FOutJoinQty"=>0.0,
                "FSecUnitId"=>[
                    "FNumber"=>""
                ],
                "FSecQty"=>0.0,
                "FBASEOUTJOINQTY"=>0.0,
                "FBaseUnitId"=>[
                    "FNumber"=>"Pcs"
                ],
                "FExtAuxUnitId"=>[
                    "FNumber"=>""
                ],
                "FExtAuxUnitQty"=>0.0,
                "FBaseQty"=>$v['goods_number'],
                "FISFREE"=>false,
                "FKeeperTypeId"=>"BD_KeeperOrg",
                "FActQty"=>0.0,
                "FKeeperId"=>[
                    "FNumber"=>config('k3cloud.organization')
                ],
                "FKeeperTypeOutId"=>"BD_KeeperOrg",
                "FKeeperOutId"=>[
                    "FNumber"=>config('k3cloud.organization')
                ],
                "FDiscountRate"=>0.0,
                "FRepairQty"=>0.0,
                "FRETURNNOTE"=>null,
                "FDestLot"=>[
                    "FNumber"=>""
                ],
                "FDestMaterialId"=>[
                    "FNumber"=>$v['goods_sn']
                ],
                "FDestBomId"=>[
                    "FNumber"=>""
                ],
                "FServiceContext"=>null,
                "FPriceUnitID"=>[
                    "FNumber"=>$v['spec_unit']
                ],
                "FPriceQty"=>$v['goods_number'],
                "FPriceBaseQty"=>$v['goods_number'],
                "FSOEntryId"=>0,
                "FQmEntryId"=>0,
                "FConvertEntryId"=>0,
                "FThirdSrcEntryId"=>null
            ];
        }
        return $goods;
    }


    /***
     * 退货仓直接调拨根据类型调拨指定仓库并提交审核
     * @param array $data
     * @param $type   1-主仓  2-次品仓
    @author echa
     * @return array|bool
     */
    public function OrderGoodsBackToWarehouse(array $data,$type){
        if(empty($data['wid'])){
            return false;
        }
        $winfo=$this->WarehouseRepository->GetWarehouseInfo($data['wid']);
        if(empty($winfo['k3_number'])){
            return false;
        }
        //主仓库编号
        $k3_number=$winfo['k3_number'];
        //退货仓库信息
        $info=$this->WarehouseService->GetWarehouseTypeInfo($k3_number,'C');
        if(empty($info[0]['FNumber'])){
            return false;
        }
        //退货仓编号
        $k3_number_t=$info[0]['FNumber'];
        $dtgoods=array();
        $dtgoods_booking=array();
        if($type==1){
            foreach ($data['goods'] as $k=>$v){
                if($v['k3_vmi']){
                    $dtgoods_booking[]=[
                        'goods_sn'=>$v['goods_sn'],
                        'spec_unit'=>$v['spec_unit'],
                        'goods_number'=>$v['goods_number'],
                        'StockNubmer'=>$k3_number_t,
                        'k3_vmi'=>$v['k3_vmi'],
                        'k3_supplier_sn'=>$v['k3_supplier_sn'],
                        'k3_vmi_out'=>$v['k3_vmi'],
                        'k3_supplier_sn_out'=>$v['k3_supplier_sn'],
                        'DestStockNubmer'=>$k3_number,
                        'goods_remark'=>'退货仓退货操作到主仓',
                    ];
                }else{
                    $dtgoods[]=[
                        'goods_sn'=>$v['goods_sn'],
                        'spec_unit'=>$v['spec_unit'],
                        'goods_number'=>$v['goods_number'],
                        'StockNubmer'=>$k3_number_t,
                        'k3_vmi'=>$v['k3_vmi'],
                        'k3_supplier_sn'=>$v['k3_supplier_sn'],
                        'k3_vmi_out'=>$v['k3_vmi'],
                        'k3_supplier_sn_out'=>$v['k3_supplier_sn'],
                        'DestStockNubmer'=>$k3_number,
                        'goods_remark'=>'退货仓退货操作到主仓',
                    ];
                }
            }
        }elseif($type==2){
            //次品仓库编号
            $cinfo=$this->WarehouseService->GetWarehouseTypeInfo($k3_number,'B');
            if(empty($cinfo[0]['FNumber'])){
                return false;
            }
            //次品仓编号
            $k3_number_c=$cinfo[0]['FNumber'];
            foreach ($data['goods'] as $k=>$v){
                if($v['k3_vmi']){
                    $dtgoods_booking[]=[
                        'goods_sn'=>$v['goods_sn'],
                        'spec_unit'=>$v['spec_unit'],
                        'goods_number'=>$v['goods_number'],
                        'StockNubmer'=>$k3_number_t,
                        'k3_vmi'=>$v['k3_vmi'],
                        'k3_supplier_sn'=>$v['k3_supplier_sn'],
                        'k3_vmi_out'=>$v['k3_vmi'],
                        'k3_supplier_sn_out'=>$v['k3_supplier_sn'],
                        'DestStockNubmer'=>$k3_number_c,
                        'goods_remark'=>'退货仓退货操作到次品仓',
                    ];
                }else{
                    $dtgoods[]=[
                        'goods_sn'=>$v['goods_sn'],
                        'spec_unit'=>$v['spec_unit'],
                        'goods_number'=>$v['goods_number'],
                        'StockNubmer'=>$k3_number_t,
                        'k3_vmi'=>$v['k3_vmi'],
                        'k3_supplier_sn'=>$v['k3_supplier_sn'],
                        'k3_vmi_out'=>$v['k3_vmi'],
                        'k3_supplier_sn_out'=>$v['k3_supplier_sn'],
                        'DestStockNubmer'=>$k3_number_c,
                        'goods_remark'=>'退货仓退货操作到次品仓',
                    ];
                }
            }
        }else{
            return false;
        }
        $returndata=array();
        if(count($dtgoods_booking)>0){
            $insert_data_booking=[
                'k3_vmi'=>1,
                'k3_supplier_sn'=>$dtgoods_booking[0]['k3_supplier_sn'],
                'k3_vmi_out'=>1,
                'k3_supplier_sn_out'=>$dtgoods_booking[0]['k3_supplier_sn'],
                'Note'=>$data['note'],
                'GoodsData'=>$dtgoods_booking
            ];
            $returnbooking=$this->SaveDirectTransfers($insert_data_booking,true);
            if(!empty($returnbooking['Id'])){
                $returndata[]=$returnbooking;
            }
        }
        if(count($dtgoods)>0){
            $insert_data=[
                'k3_vmi'=>0,
                'k3_supplier_sn'=>$dtgoods[0]['k3_supplier_sn'],
                'k3_vmi_out'=>0,
                'k3_supplier_sn_out'=>$dtgoods[0]['k3_supplier_sn'],
                'Note'=>$data['note'],
                'GoodsData'=>$dtgoods
            ];
            $return=$this->SaveDirectTransfers($insert_data,true);
            if(!empty($return['Id'])){
                $returndata[]=$return;
            }
        }
        if(count($returndata)>0){
            return $returndata;
        }else{
            return false;
        }
    }

    /***
     * 主仓操作次品录入直接调拨到次品仓
     * @param array $data
    @author echa
     * @return array|bool
     */
    public function DefectiveGoodsEntry(array $data){
        if(empty($data['wid'])){
            return false;
        }
        $winfo=$this->WarehouseRepository->GetWarehouseInfo($data['wid']);
        if(empty($winfo['k3_number'])){
            return false;
        }
        //主仓库编号
        $k3_number=$winfo['k3_number'];
        //次品仓库编号
        $cinfo=$this->WarehouseService->GetWarehouseTypeInfo($k3_number,'B');
        if(empty($cinfo[0]['FNumber'])){
            return false;
        }
        //次品仓编号
        $k3_number_c=$cinfo[0]['FNumber'];
        if(count($data['goods'])){
            $dtgoods=array();
            $dtgoods_booking=array();
            foreach ($data['goods'] as $k=>$v){
                if($v['k3_vmi']){
                    $dtgoods_booking[]=[
                        'goods_sn'=>$v['goods_sn'],
                        'spec_unit'=>$v['spec_unit'],
                        'goods_number'=>$v['goods_number'],
                        'StockNubmer'=>$k3_number,
                        'k3_vmi'=>$v['k3_vmi'],
                        'k3_supplier_sn'=>$v['k3_supplier_sn'],
                        'k3_vmi_out'=>$v['k3_vmi'],
                        'k3_supplier_sn_out'=>$v['k3_supplier_sn'],
                        'DestStockNubmer'=>$k3_number_c,
                        'goods_remark'=>'主仓操作次品录入到次品仓',
                    ];
                }else{
                    $dtgoods[]=[
                        'goods_sn'=>$v['goods_sn'],
                        'spec_unit'=>$v['spec_unit'],
                        'goods_number'=>$v['goods_number'],
                        'StockNubmer'=>$k3_number,
                        'k3_vmi'=>$v['k3_vmi'],
                        'k3_supplier_sn'=>$v['k3_supplier_sn'],
                        'k3_vmi_out'=>$v['k3_vmi'],
                        'k3_supplier_sn_out'=>$v['k3_supplier_sn'],
                        'DestStockNubmer'=>$k3_number_c,
                        'goods_remark'=>'主仓操作次品录入到次品仓',
                    ];
                }
            }
            $returndata=array();
            if(count($dtgoods_booking)>0){
                $insert_data_booking=[
                    'k3_vmi'=>1,
                    'k3_supplier_sn'=>$dtgoods_booking[0]['k3_supplier_sn'],
                    'k3_vmi_out'=>1,
                    'k3_supplier_sn_out'=>$dtgoods_booking[0]['k3_supplier_sn'],
                    'Note'=>$data['note'],
                    'GoodsData'=>$dtgoods_booking
                ];
                $returnbooking=$this->SaveDirectTransfers($insert_data_booking,true);
                if(!empty($returnbooking['Id'])){
                    $returndata[]=$returnbooking;
                }
            }
            if(count($dtgoods)>0){
                $insert_data=[
                    'k3_vmi'=>0,
                    'k3_supplier_sn'=>$dtgoods[0]['k3_supplier_sn'],
                    'k3_vmi_out'=>0,
                    'k3_supplier_sn_out'=>$dtgoods[0]['k3_supplier_sn'],
                    'Note'=>$data['note'],
                    'GoodsData'=>$dtgoods
                ];
                $return=$this->SaveDirectTransfers($insert_data,true);
                if(!empty($return['Id'])){
                    $returndata[]=$return;
                }
            }
            if(count($returndata)>0){
                return $returndata;
            }else{
                return false;
            }
        }else{
            return false;
        }
    }
}